#include "RegReader.h"
#include <algorithm>
#include <iostream>
#include <fstream>
using namespace std;

typedef struct  regSimple
{
	int index;
	SYSTEMTIME st;
}regSimple; 

int compare(const void *a, const void *b);
void sort(vector<RegKeyTime> &out);


int main(int argc, char *argv[])
{
	RegReader regReader;
	vector<RegKeyTime> out;

	ofstream fout;
 #ifdef _DEBUG
 	argc = 3;
 	argv[1] = "\\";//"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion";
 	argv[2] = "result.csv";
	char *paths[] = { "HKEY_CLASSES_ROOT\\", "HKEY_CURRENT_USER\\", "HKEY_LOCAL_MACHINE\\",  
		"HKEY_USERS\\", "HKEY_CURRENT_CONFIG\\" };
	for(int i=0; i<5; i++){
		out.clear();
		regReader.queryKey(paths[i], out);
	}
#endif
	if (argc > 2)
	{
		regReader.queryKey(argv[1],out);
		fout.open(argv[2]);
	}
	else
	{
		char path[256];
		cin >> path;
		regReader.queryKey(path,out);
		fout.open("result.csv");
	}

	sort(out);


	for (int i = 0; i < out.size(); ++i)
	{
		fout << out[i].regKeyLastWriteTime.wYear << ','
				<< out[i].regKeyLastWriteTime.wMonth << ','
				<< out[i].regKeyLastWriteTime.wDay << ','
				<< out[i].regKeyLastWriteTime.wHour << ','
				<< out[i].regKeyLastWriteTime.wMinute << ','
				<< out[i].regKeyLastWriteTime.wSecond << ','
				<< out[i].regKeyLastWriteTime.wMilliseconds <<  ','
				<< out[i].regKeyPath << '\n';
	}
	return 0;	
}



int mycompare(const void *a, const void *b)
{
	SYSTEMTIME sa = ((regSimple*)a)->st;
	SYSTEMTIME sb = ((regSimple*)b)->st;
	int diff[7];
	int index = 0;
	diff[0] = sa.wYear - sb.wYear;
	diff[1] = sa.wMonth - sb.wMonth;
	diff[2] = sa.wDay - sb.wDay;
	diff[3] = sa.wHour - sb.wHour;
	diff[4] = sa.wMinute - sb.wMinute;
	diff[5] = sa.wSecond - sb.wSecond;
	diff[6] = sa.wMilliseconds - sb.wMilliseconds;

	while(diff[index++] == 0);
	
	return (diff[index-1]>0)?-1:1;
}

void sort(vector<RegKeyTime> &out)
{
	vector<RegKeyTime> temp(out);
	int sz = temp.size();
	
	regSimple *rs = new regSimple[sz];

	for (int i = 0; i < sz; ++i)
	{
		rs[i].index = i;
		rs[i].st = out[i].regKeyLastWriteTime;
	}

	qsort(rs,sz,sizeof(regSimple),mycompare);

	for (int i = 0; i < sz; ++i)
	{
		out[i] = temp[rs[i].index];
	}

	return;
}

void test()
{

}